package at.fhj.itm.controller;


import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Vector;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.List;
import javax.microedition.rms.InvalidRecordIDException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreFullException;
import javax.microedition.rms.RecordStoreNotFoundException;
import javax.microedition.rms.RecordStoreNotOpenException;

import at.fhj.itm.model.Translator;
import at.fhj.itm.model.VocabEntry;
import at.fhj.itm.view.TranslationBoxV2;

public class DictControllerV2 implements CommandListener, Runnable
{
	private Translator translator;
	private Vector vocabVector;
	private RecordEnumeration records;
	private TranslationBoxV2 dictionaryView;
	public static final String RECORDSTORE_NAME="TheDictionary-Begleiter";
	public static final String VOCABFILE_NAME="Vokabel.txt";
	public static final String ABOUTFILE_NAME="about.txt";
	public static final String HELPFILE_NAME="help.txt";
	
	
	public DictControllerV2(TranslationBoxV2 dictionaryView)
	{	
		this.dictionaryView= dictionaryView;
		translator=new Translator();
		vocabVector = new Vector(10);		
	}

	public void commandAction(Command c, Displayable d) 
	{
		if(c==dictionaryView.exitC)
		{
			//TODO: close the record store
			
			dictionaryView.notifyDestroyed();
		}
		
		if(c==dictionaryView.backC)
		{
			//if it is called from the entry form 
			if(d.getTitle().equals(TranslationBoxV2.ENTRY_SCR_TITLE))
			{
				dictionaryView.getEntryScr().deleteAll();
				dictionaryView.setCurrentScreen(dictionaryView.getVocabSuggestions());
			}
			else if(d.getTitle().equals(TranslationBoxV2.VOCAB_SUGGEST_TITLE))
			{
				dictionaryView.setCurrentScreen(dictionaryView.getSearchScr());
			}
			else if(d.getTitle().equals(TranslationBoxV2.SEARCH_SCR_TITLE))
			{
				dictionaryView.setCurrentScreen(dictionaryView.getMainScr());
			}
			else if(d.getTitle().equals(TranslationBoxV2.HELP_SCR_TITLE))
			{
				dictionaryView.setCurrentScreen(dictionaryView.getMainScr());
			}
			else if(d.getTitle().equals(TranslationBoxV2.ABOUT_SCR_TITLE))
			{
				dictionaryView.setCurrentScreen(dictionaryView.getMainScr());
			}
		}
		
		else if(c==dictionaryView.startC)
		{
			List mainScreen = (List)dictionaryView.getMainScr();

			if(mainScreen.getSelectedIndex()==TranslationBoxV2.START_INDEX)
			{
				dictionaryView.setSearchScr(dictionaryView.genSearchScr());
				dictionaryView.setCurrentScreen(dictionaryView.genSearchScr());				
			}
			else if(mainScreen.getSelectedIndex()==TranslationBoxV2.ABOUT_INDEX)
			{				
				dictionaryView.setAboutText(readTextFromResource(ABOUTFILE_NAME));
				dictionaryView.setAboutScr((Form)dictionaryView.genAboutScreen());
				dictionaryView.setCurrentScreen(dictionaryView.getAboutScr());
			}
			else if(mainScreen.getSelectedIndex()==TranslationBoxV2.HELP_INDEX)
			{
				dictionaryView.setHelpText(readTextFromResource(HELPFILE_NAME));
				dictionaryView.setHelpScr((Form)dictionaryView.genHelpScreen());
				dictionaryView.setCurrentScreen(dictionaryView.getHelpScr());
			}
		}		
		else if(c==dictionaryView.searchC)
		{			
			Thread vocabSuggestionsThread = new Thread(this);
			vocabSuggestionsThread.start();
		}
		else if(c==dictionaryView.translateC)
		{
			if(dictionaryView.getVocabSuggestions().size()>0)
			{
				Integer recordID = (Integer)vocabVector.
				elementAt(dictionaryView.getVocabSuggestions().getSelectedIndex());
				//use buffer to save memory
				StringBuffer translation =new StringBuffer();
				
				try {
					translation.append(translator.lookupMeaning(translator.getVocabEntries().
							getRecord(recordID.intValue())));
				} catch (Exception e){
					System.out.println(e.getMessage());
				}				
				
				dictionaryView.setEntryScr((Form)dictionaryView.genEntryScr());
				dictionaryView.getEntryScr().append(translation.toString());
				dictionaryView.setCurrentScreen(dictionaryView.getEntryScr());
				//reset the buffer
				translation.delete(0, translation.length());
			}
		}
	}

	public void run() {
		
		//if run for the first time, then set a record store and open 						
		if(translator.getVocabEntries()==null)
		{
			try
			{								
				translator.setVocabEntries(RecordStore.openRecordStore(RECORDSTORE_NAME, true));				
			} catch (RecordStoreFullException e) {				
				e.printStackTrace();
			} catch (RecordStoreNotFoundException e) {				
				e.printStackTrace();
			} catch (RecordStoreException e) {				
				e.printStackTrace();
			} 
		}
		//if the Record Store is empty: store vocabs into it
		try {
			if(translator.getVocabEntries().getNumRecords()==0)
			{
				translator.readFromPackagedFile();
				System.out.println("----------------------- entries are read");
			}
		} catch (RecordStoreNotOpenException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}				
		
		/*if the user input string is empty then it displays all vocabs matching "a",
		 * otherwise all vocabs that start with the entered search string
		 */		
		records=translator.makeSuggestions(dictionaryView.getSearchData().getString());
		
		dictionaryView.setVocabSuggestions(dictionaryView.genVocabSuggestionsList());
		dictionaryView.setCurrentScreen(dictionaryView.getVocabSuggestions());
		
		int nextRecordID = 0;
		
		dictionaryView.getVocabSuggestions().append("contains amount of records: "+records.numRecords(), null);
		if(records.hasNextElement())
		{	
			byte[] nextRecord=null;
			
			while(records.hasNextElement())
			{
				/*take the record and add its german value as item 
				 * on the view's suggestion list
				 */	
				
				try {
					nextRecordID=records.nextRecordId();
					nextRecord=translator.getVocabEntries().getRecord(nextRecordID);
					System.out.println("-------------------- record length: "+nextRecord.length);
					System.out.println("-------------------------------- got nextRecord, german: "+VocabEntry.getWord(nextRecord));
				} catch (Exception e)
				{
					System.out.println(e.getMessage()+"----------------------------");
				}
				/* add the german vocab to a vector, to select the element at the index
				 * of this vector which is the record to the shown list entry that the
				 * user selected  
				 */
				Integer recordID = new Integer(nextRecordID);
				vocabVector.addElement(recordID);
				System.out.println("------------------ added record id for vocab to vector");
				recordID=null;				
				
				String german=VocabEntry.getWord(nextRecord);
				System.out.println("------------------------ got german word");
				dictionaryView.getVocabSuggestions().append(german, null);				
			}
		}
		else
		{			
			dictionaryView.getVocabSuggestions().append("Keine passenden Einträge gefunden!", null);			
		}
	}
	
	public String readTextFromResource(String filename)
	{
		//read program description from resource file
		InputStreamReader inr=null;
		InputStream in =this.getClass().getResourceAsStream("/"+filename);			   
		try {
			inr = new InputStreamReader(in, "UTF8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		StringBuffer buffer = new StringBuffer();
		int charCode=0;
		try {
			while((charCode=inr.read())>-1)
			{
				buffer.append((char)charCode);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	
	public void deleteRS()
	{
		try {
			translator.getVocabEntries().closeRecordStore();
			RecordStore.deleteRecordStore(RECORDSTORE_NAME);
		} catch (RecordStoreNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (RecordStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


}
